#include <stdio.h>
#include "pcb.h"
#include "sim.h"
#include "sched0.h"
#include "doubleL.h"

list* wait_queue;
list* block_queue;

static int findAndRemove(list* q, PCB* p){
	int i;

	for(i=1;i<=list_length(q);i++){
		if(((PCB*) list_get_element(q, i))->pid == p->pid){
			list_remove(q, i);
			return 1;
		}
	}
	return 0;
}

PCB* handleEvent0(Event e, PCB* p)
{
	PCB* tmp;

	switch(e){
		case TERMPROC:
			
			if(!list_empty(wait_queue) && ((PCB*) list_get_element(wait_queue, 1))->pid == p->pid)
			{
				list_remove(wait_queue, 1);
			}
			break;
		case TERMSLICE:
			break;
		case IOSTART:
			tmp = (PCB*) list_get_element(wait_queue, 1);
			list_remove(wait_queue, 1);
			list_append(block_queue, (ElemType) p);
			break;
		case IOCOMPLETE:
			if(!isProcessComplete(p)){
				list_append(wait_queue, (ElemType) p);
			}
			findAndRemove(block_queue, p);
			break;
		case PROCESSSTART:
			list_append(wait_queue, (ElemType) p); 
			break;
	}

	if(!list_empty(wait_queue) ){
		tmp = (PCB*) list_get_element(wait_queue, 1);
		tmp->time_slice = 30000;
		return tmp;
	} else {
		return NULL;
	}
}

void initSched0()
{
	wait_queue = list_init();
	block_queue = list_init();
}
